package jp.co.ziro.wikidozan.controller;

import java.util.LinkedList;
import java.util.List;

public class UriPath {

    public static final String DEFAULT_ACTION = "default";

    private String controller;

    private String action;

    private String id;

    private String ids;

    private List idsAsList;

    public UriPath(String uri) {
        if (uri.startsWith("/")) {
            uri = uri.substring(1);
        }
        String[] tokens = uri.split("/");

        this.controller = tokens.length >= 1 ? tokens[0] : null;
        this.action = tokens.length >= 2 ? tokens[1] : DEFAULT_ACTION;
        this.id = tokens.length >= 3 ? tokens[2] : null;
        this.ids = id;

        this.idsAsList = new LinkedList();
        if (id != null) {
            this.idsAsList.add(id);
        }
        for (int i = 3; i < tokens.length; i++) {
            this.ids += "/" + tokens[i];
            idsAsList.add(tokens[i]);
        }

        // reset if empty controller
        this.controller = this.controller.length() == 0 ? null
                : this.controller;
    }

    public UriPath(String controller, String action, String ids) {
        this(controller + "/" + action + "/" + ids);
    }

    /**
     * Returns the mapping for the controller (the first element after the
     * leading slash in a URI.
     * 
     * @return The controller mapping as specified in the URI or
     *         <code>null</code> if root (slash only) was specified.
     */
    public String getController() {
        return controller;
    }

    /**
     * Returns the action as specified as the second URI element.
     * 
     * @return The action as specified in the URI or {@link #DEFAULT_ACTION}
     *         if no action was specified.
     */
    public String getAction() {
        return action;
    }

    /**
     * Returns the id specified as third element of the URI.
     * 
     * @return The id or <code>null</code> if not specified.
     */
    public String getId() {
        return id;
    }

    /**
     * Returns all specified ids concatenated by '/';
     * 
     * @return All ids or <code>null</code> if no ids specified
     */
    public String getIds() {
        return ids;
    }

    /**
     * Sets a new value for the path id (the 3rd component of the url).
     * 
     * @param id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * Returns list of ids specified.
     * 
     * @return A list of ids. List can be empty, never <code>null</code>.
     */
    public List getIdsAsList() {
        return idsAsList;
    }
}